<template>
  <div class="data-table">
    <div class="table-controls">
      <input v-model="searchQuery" type="text" placeholder="搜索..." class="search-input" />
      <div class="filter-options">
        <label>
          <input v-model="showActive" type="checkbox" />
          只显示激活状态
        </label>
      </div>
    </div>

    <table>
      <thead>
        <tr>
          <th
            v-for="column in columns"
            :key="column.key"
            @click="sortBy(column.key)"
            :class="{ sortable: column.sortable, active: currentSort === column.key }"
          >
            {{ column.label }}
            <span v-if="currentSort === column.key" class="sort-icon">
              {{ currentSortDir === 'asc' ? '↑' : '↓' }}
            </span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in filteredAndSortedData" :key="item.id">
          <td v-for="column in columns" :key="column.key">
            {{ item[column.key] }}
          </td>
        </tr>
      </tbody>
      <tfoot v-if="filteredAndSortedData.length === 0">
        <tr>
          <td :colspan="columns.length" class="no-data">没有找到匹配的数据</td>
        </tr>
      </tfoot>
    </table>

    <div class="table-footer">
      <span>总条目: {{ filteredAndSortedData.length }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'

  // 定义数据项的类型
  interface TableItem {
    id: number
    name: string
    email: string
    status: 'active' | 'inactive'
    createdAt: string
    [key: string]: string | number | boolean
  }

  // 定义表格列的类型
  interface TableColumn {
    key: string
    label: string
    sortable: boolean
  }

  // 定义组件属性
  const props = defineProps<{
    initialData?: TableItem[]
  }>()

  // 列定义
  const columns: TableColumn[] = [
    { key: 'id', label: 'ID', sortable: true },
    { key: 'name', label: '姓名', sortable: true },
    { key: 'email', label: '邮箱', sortable: true },
    { key: 'status', label: '状态', sortable: true },
    { key: 'createdAt', label: '创建日期', sortable: true }
  ]

  // 状态变量
  const tableData = ref<TableItem[]>([])
  const searchQuery = ref('')
  const currentSort = ref('id')
  const currentSortDir = ref<'asc' | 'desc'>('asc')
  const showActive = ref(false)

  // 模拟API调用获取数据
  const fetchData = (): Promise<TableItem[]> =>
    new Promise(resolve => {
      setTimeout(() => {
        resolve([
          {
            id: 1,
            name: '张三',
            email: 'zhangsan@example.com',
            status: 'active',
            createdAt: '2023-01-15'
          },
          {
            id: 2,
            name: '李四',
            email: 'lisi@example.com',
            status: 'inactive',
            createdAt: '2023-02-20'
          },
          {
            id: 3,
            name: '王五',
            email: 'wangwu@example.com',
            status: 'active',
            createdAt: '2023-03-10'
          },
          {
            id: 4,
            name: '赵六',
            email: 'zhaoliu@example.com',
            status: 'active',
            createdAt: '2023-04-05'
          }
        ])
      }, 500)
    })

  // 生命周期钩子
  onMounted(async () => {
    // 如果有传入的初始数据，则使用它，否则从API获取
    if (props.initialData && props.initialData.length) {
      tableData.value = [...props.initialData]
    } else {
      try {
        tableData.value = await fetchData()
        console.warn('数据加载完成')
      } catch (error) {
        console.error('加载数据时发生错误:', error)
      }
    }
  })

  // 监听搜索查询变化
  watch(searchQuery, () => {
    console.warn('搜索查询已更新', searchQuery.value)
  })

  // 计算属性: 根据搜索和过滤条件过滤数据
  const filteredData = computed(() => {
    let result = [...tableData.value]

    // 根据搜索条件过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter(
        item => item.name.toLowerCase().includes(query) || item.email.toLowerCase().includes(query)
      )
    }

    // 根据激活状态过滤
    if (showActive.value) {
      result = result.filter(item => item.status === 'active')
    }

    return result
  })

  // 计算属性: 根据当前排序方式对过滤后的数据进行排序
  const filteredAndSortedData = computed(() =>
    [...filteredData.value].sort((a, b) => {
      const modifier = currentSortDir.value === 'asc' ? 1 : -1
      const aValue = a[currentSort.value]
      const bValue = b[currentSort.value]

      if (aValue < bValue) return -1 * modifier
      if (aValue > bValue) return 1 * modifier
      return 0
    })
  )

  // 根据列排序
  function sortBy(key: string) {
    // 如果点击的是当前排序的列，则翻转排序方向
    if (key === currentSort.value) {
      currentSortDir.value = currentSortDir.value === 'asc' ? 'desc' : 'asc'
    } else {
      // 否则，按新列排序并默认使用升序
      currentSort.value = key
      currentSortDir.value = 'asc'
    }
  }
</script>

<style scoped>
  .data-table {
    width: 100%;
    margin: 20px 0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .table-controls {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    background-color: #f5f5f5;
    border-bottom: 1px solid #ddd;
  }

  .search-input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 200px;
  }

  table {
    width: 100%;
    border-collapse: collapse;
  }

  th,
  td {
    padding: 12px 15px;
    text-align: left;
    border-bottom: 1px solid #ddd;
  }

  th {
    background-color: #f9f9f9;
    font-weight: bold;
  }

  th.sortable {
    cursor: pointer;
    user-select: none;
  }

  th.active {
    background-color: #e9e9e9;
  }

  tr:hover {
    background-color: #f5f5f5;
  }

  .table-footer {
    padding: 10px 15px;
    background-color: #f9f9f9;
    font-weight: bold;
    display: flex;
    justify-content: flex-end;
  }

  .sort-icon {
    margin-left: 5px;
    font-weight: bold;
  }

  .no-data {
    text-align: center;
    padding: 20px;
    font-style: italic;
    color: #999;
  }

  .filter-options {
    display: flex;
    align-items: center;
  }
</style>
